﻿using Microsoft.Exchange.WebServices.Data;
using MimeKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace EmailHelper.Exchange
{
    /// <summary>
    /// MimeMessage帮助类
    /// </summary>
    public class MimeMessageHelper
    {
        /// <summary>
        /// exchange消息对象 转 MimeMessage
        /// </summary>
        /// <param name="emailMessage"></param>
        /// <returns></returns>
        public static MimeMessage MessageTypeToMimeMessage(EmailMessage emailMessage)
        {
            try
            {
                byte[] bytes = emailMessage.MimeContent?.Content;
                //var mime = MimeMessage.Load(new MemoryStream(bytes));
                var mime = new MimeParser(new MemoryStream(bytes)).ParseMessage();
                return mime;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// exchange消息对象 转 MimeMessage
        /// </summary>
        /// <param name="emailMessage"></param>
        /// <returns></returns>
        public static MimeMessage MessageByteToMimeMessage(byte[] mailBodyContent)
        {
            try
            {
                var message = new MimeParser(new MemoryStream(mailBodyContent)).ParseMessage();
                return message;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}